<template>
  <div>
    <el-container>
      <el-header style="height: auto;">
        <el-form :inline="true" style="margin-top: 10px">
          <el-form-item label="选择项目" class="mt-form-item-left">
            <el-select
              v-model="project_id"
              v-loading="projectsLoading"
              placeholder="选择项目"
              filterable
              clearable
              @change="handleChangeProject"
            >
              <el-option label="我的" value="mine" />
              <el-option label="所有" value="" />
              <el-option
                v-for="(item,index) in projects"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择网站" class="mt-form-item-left">
            <!--            <el-select v-model="select_web" placeholder="选择网站" filterable clearable @change="handleChangeWeb">-->
            <!--              <el-option label="所有" value="">-->
            <!--              </el-option>-->
            <!--              <el-option v-for="(item,index) in websites" :key="index" :label="item.domain"-->
            <!--                         :value="item.id">-->
            <!--              </el-option>-->
            <!--            </el-select>-->
            <el-select
              v-model="select_web"
              filterable
              clearable
              remote
              value-key="label"
              reserve-keyword
              placeholder="输入域名搜索网站"
              :remote-method="remoteSearchWebsite"
              :loading="remoteSearchWebsite_loading"
              @change="handleChangeWeb"
            >
              <el-option
                v-for="(item,index) in website_options"
                :key="index"
                :label="item.domain"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="select_web > 0" label="选择状态" class="mt-form-item-left">
            <el-select v-model="selected_status" multiple clearable>
              <el-option
                v-for="(item,index) in dataStatus"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-else label="选择状态" class="mt-form-item-left">
            <el-select v-model="selected_status" multiple clearable>
              <el-option
                v-for="(item,index) in common_dataStatus"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="timerange"
              type="datetimerange"
              value-format="timestamp"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              :default-time="['0:00:00', '23:59:59']"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item class="mt-form-item-search">
            <el-input
              v-model="kwInput"
              placeholder="搜索关键词"
              clearable
              :autosize="{ minRows: 4}"
              @keyup.native.enter="handleGetOrders"
            />
          </el-form-item>

          <el-form-item style="width:100px;">
            <el-button type="primary" style="float: right;" @click="handleGetOrders">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-form :inline="true" style="margin-top: 0px">
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="handleSearchByPayment">交易搜索</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="handleRefund">退款</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="handleSearchShipping">发货搜索</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="handleAliexpressOrders">速卖通订单</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="orderswebVisible=true">订单网站</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="trackingfilesVisible=true">跟踪文件</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button style="float: right;" @click="blackaddressVisible=true">黑名单</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button v-if="select_web > 0" type="warning" style="float: left" @click="handleSyncOrders()">同步订单
            </el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button
              v-if="select_web > 0"
              type="success"
              style="float: left"
              :loading="statesyncloading"
              @click="handleSyncOrderState"
            >
              同步状态
            </el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button v-if="select_web > 0" type="primary" style="float: left" @click="handleStatics">
              统计信息
            </el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button v-if="select_web > 0" type="primary" style="float: left" @click="handleShowOrderDetailAll">
              出单统计
            </el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table
          v-loading="loading"
          :data="order_datas"
          border
          :row-style="tableRowStyle"
          :cell-style="tableCellStyle"
          :default-sort="{prop: 'order_time', order: 'descending'}"
          style="width: 100%;border:2px solid black;color:black"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column align="center" label="订单信息" width="250px">
            <template slot-scope="scope">
              {{ scope.row.reference }} {{ scope.row.id_order }} <i
                class="el-icon-refresh"
                @click="handleReFreshOrder(scope.row)"
              /><br>
              网站:
              <el-tag type="primary" @click="handleSingleStatics(scope.row.website_id)">{{ scope.row.domain }}</el-tag>
              <br>
              <span style="color:#FF0000;">
                <i class="el-icon-date">{{ scope.row.create_at.split('T')[0] }}</i>
                <i class="el-icon-time">{{ scope.row.create_at.split('T')[1] }}</i>
              </span>
              <br>
              <el-tag title="显示邮件" @click="handleShowMail(scope.row)">{{ scope.row.email }}</el-tag>
              <br>
              <el-button size="mini" type="text" @click="handleReplyMail(scope.row)">回复</el-button>
              <el-button size="mini" type="text" @click="handleReFreshOrder(scope.row)">同步
              </el-button>
              <el-button
                v-if="scope.row.show_able"
                size="mini"
                type="text"
                @click="handleHiddenOrder(scope.row)"
              >删除
              </el-button>
              <el-button
                v-else
                size="mini"
                type="text"
                @click="handleHiddenOrder(scope.row)"
              >恢复
              </el-button>
              <el-button
                v-if="!scope.row.died"
                size="mini"
                type="text"
                @click="handleDiedOrder(scope.row)"
              >死单
              </el-button>
              <el-button
                v-else
                size="mini"
                type="text"
                @click="handleDiedOrder(scope.row)"
              >活单
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="地址信息" width="250px">
            <template slot-scope="scope">
              <span v-if="scope.row.id_transaction !== '' && scope.row.is_valid_order" style="color:#FF0000;">
                <strong>
                  {{ scope.row.firstname }} {{ scope.row.lastname }}<br>
                  <span v-if="scope.row.company">{{ scope.row.company }}<br></span>
                  <span v-if="scope.row.address2">{{ scope.row.address2 }}<br></span>
                  {{ scope.row.address1 }}<br>
                  {{ scope.row.country_statename }},{{ scope.row.city }},{{ scope.row.postcode }}<br>
                  {{ scope.row.country }}<br>
                  {{ scope.row.phone }}<br>
                </strong>
              </span>
              <span v-else>
                <el-alert
                  :title="'也许是支付失败的订单,请核实 当前状态:' + scope.row.state_name"
                  type="warning"
                  :closable="false"
                  show-icon
                />
              </span>
              <br>
              <el-row>
                <el-col>
                  <span>系统ID:</span><span>{{ scope.row.id }}</span>
                </el-col>
                <el-col>
                  <el-alert
                    v-if="scope.row.in_blackaddress"
                    :title="'高风险:' + scope.row.blackaddress_msg"
                    type="error"
                    :closable="false"
                    effect="dark"
                  />
                  <el-popconfirm
                    v-else
                    title="确定要将改订单地址加入黑名单吗？"
                    @confirm="handleAddOrderToBlackAddress(scope.row)"
                  >
                    <el-button slot="reference" type="text" size="mini">拉黑</el-button>
                  </el-popconfirm>
                </el-col>
              </el-row>
              <br>
              <!--<el-button type="text" size="mini" @click="getAddressJs(scope.row)">获取地址代码</el-button>-->
            </template>
          </el-table-column>
          <el-table-column align="left" label="产品信息">
            <template slot-scope="scope">
              <span> {{ scope.row.currency }}{{ scope.row.total_paid }} 运费:<span
                style="color:#FF0000"
              >{{ scope.row.currency }}{{ scope.row.total_shipping }}</span></span>
              <span>{{ scope.row.carrier }}</span>
              <el-table :data="scope.row.products" size="mini" border fit style="width: 100%;color:#075DB3;">
                <el-table-column
                  align="center"
                  width="65px"
                  prop="image"
                  label="图片"
                  @click="handleShowProductDetail(scope.row)"
                >
                  <template slot-scope="scope">
                    <img
                      :src="scope.row.image"
                      style="max-width: 50px; max-height: 50px"
                      @click="handleShowProductDetail(scope.row)"
                    >
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="product_name" label="产品">
                  <template slot-scope="scope">
                    <a v-if="scope.row.ps_url" :href="scope.row.ps_url" target="_blank">{{ scope.row.product_name }}</a>
                    <span v-else>{{ scope.row.product_name }}</span>
                    <!--<a v-if="scope.row.product_url" :href="scope.row.product_url+'?erporderid='+scope.row.order_id" target="_blank"> 采购</a>-->
                    <!--<span v-else>{{scope.row.product_url}}</span>-->
                  </template>
                </el-table-column>
                <el-table-column align="center" width="80px" prop="product_quantity" label="数量/ID">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="handleShowProductDetail(scope.row)">
                      {{ scope.row.product_quantity }}
                    </el-button>
                    <el-button type="text" size="mini" @click="handleShowFastModifyFeed(scope.row)">
                      {{ scope.row.product_id }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column align="center" width="80px" prop="product_url" label="供应商">
                  <template slot-scope="scope">
                    <!--<el-button type="text" size="mini" @click="handleShowGoogleConversion(scope.row)">{{scope.row.google_conversion_count}}-->
                    <!--</el-button>-->
                    <el-button type="text" size="mini" @click="handleShowSupplier(scope.row)">查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                v-if="scope.row.id_transaction === ''"
                icon="el-icon-search"
                size="mini"
                type="text"
                @click="handleGetPayment(scope.row)"
              >获取交易号
              </el-button>
              <el-tag v-else size="medium" type="success">{{ scope.row.payment_name }}
                账号:{{ scope.row.paypal_api_account }}
                交易号: {{ scope.row.id_transaction }}
              </el-tag>
              <el-button
                v-if="scope.row.payment_name.indexOf('PacyPay') >= 0"
                size="mini"
                type="text"
                @click="GetOrderPaymentStatus(scope.row)"
              >支付状态
              </el-button>
              <el-tag v-if="scope.row.refund_amount" type="danger">已退款:{{ scope.row.refund_amount }}</el-tag>
              <el-button
                v-if="scope.row.psorderpayment_id !== ''"
                icon="el-icon-plus"
                size="mini"
                type="text"
                @click="showRefund(scope.row)"
              >退款
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="left" label="发货信息">
            <template slot-scope="scope">
              <ul
                v-for="(item,index) in scope.row.trackings"
                v-if="scope.row.trackings.length > 0"
                :key="index"
                style="padding-left: 0px;"
              >
                <li v-if="item.dropshipping_account !== ''" style="list-style:none">采购账号:{{ item.dropshipping_account }}
                  快递:{{ item.carrier }}
                </li>
                <li v-if="item.dropshipping_order_id !== ''" style="list-style:none">
                  订单ID:
                  <a
                    target="_blank"
                    :href="'https://trade.aliexpress.com/order_detail.htm?&orderId='+item.dropshipping_order_id"
                  >{{
                    item.dropshipping_order_id
                  }}</a>
                </li>
                <li v-if="item.order_state !== ''" style="list-style:none">{{ item.order_state }}</li>
                <li v-if="item.tracking_no !== ''" style="list-style:none">
                  跟踪单号:<span v-if="item.tracking_url !== ''"><a
                    :href="'https://global.cainiao.com/detail.htm?mailNoList=' + scope.row.tracking_no"
                    target="_blank"
                  >{{ item.tracking_no }}</a></span>
                  <span v-else>{{ item.tracking_no }}</span></li>
                <li v-if="item.specify_tracking_no !== ''" style="list-style:none">
                  指定跟踪单号:<span v-if="item.specify_tracking_no !== ''"><a
                    :href="'https://t.17track.net/en#nums=' + item.specify_tracking_no"
                    target="_blank"
                  >{{ item.specify_tracking_no }}</a></span>
                  <span v-else>{{ item.specify_tracking_no }}</span>
                </li>
                <li v-if="item.tracking_no_duplicate" style="list-style:none">
                  <el-tag type="danger">跟踪单号重复</el-tag>
                </li>
                <li v-if="item.order_at !== ''" style="list-style:none">下单时间:{{ item.order_at }} By
                  {{ scope.row.operator }}
                </li>
              </ul>
              <ul v-else style="padding-left: 0px;">
                <li v-if="scope.row.dropshipping_account !== ''" style="list-style:none">
                  <a
                    target="_blank"
                    :href="'https://trade.aliexpress.com/order_detail.htm?&orderId='+scope.row.dropshipping_order_id"
                  >{{
                    scope.row.dropshipping_account
                  }}采购<br>订单ID:{{ scope.row.dropshipping_order_id }}</a>
                </li>
                <li v-if="scope.row.dropshipping_msg !== ''" style="list-style:none">{{ scope.row.dropshipping_msg }}
                </li>
                <li v-if="scope.row.tracking_no !== ''" style="list-style:none">
                  跟踪单号:<span v-if="scope.row.tracking_url !== ''"><a
                    :href="scope.row.tracking_url"
                    target="_blank"
                  >{{
                    scope.row.tracking_no
                  }}</a></span>
                  <span v-else>{{ scope.row.tracking_no }}</span></li>
                <li v-if="scope.row.operator !== ''" style="list-style:none">By {{ scope.row.operator }}</li>
              </ul>
              <!--<el-tag type="warning" v-if="scope.row.note != ''" @click="addnote(scope.row)">{{scope.row.note}}</el-tag>-->
              <el-button
                v-if="!scope.row.is_shipping"
                icon="el-icon-edit"
                size="mini"
                type="danger"
                @click="handleShipped(scope.row)"
              >
                发送货物
              </el-button>
              <el-button
                v-else-if="!scope.row.shipping_company_order_id"
                icon="el-icon-edit"
                size="mini"
                type="success"
                @click="handleShipped(scope.row)"
              >
                查看/修改快递信息
              </el-button>
              <el-button v-else icon="el-icon-edit" size="mini" type="warning" @click="handleShipped(scope.row)">修改信息
              </el-button>
              <br>
              <hr>
              <el-button
                v-if="scope.row.note != ''"
                style="float: left"
                type="danger"
                plain
                size="mini"
                @click="addnote(scope.row)"
              >
                {{ scope.row.note }}
              </el-button>
              <el-button v-else type="text" size="mini" @click="addnote(scope.row)">添加备注</el-button>
              <div v-if="scope.row.customer_emails > 0">
                <el-popover
                  placement="left"
                  width="640"
                  trigger="hover"
                >
                  <div>
                    <div style="margin-top: 10px">
                      <el-input v-model="scope.row.latest_email" type="textarea" rows="20" />
                    </div>
                  </div>
                  <el-tag slot="reference" style="display: inline-block; float: right" type="warning">
                    有客户邮件{{ scope.row.customer_emails }}封
                  </el-tag>
                </el-popover>
              </div>
              <br>
              <hr>
              <el-select
                v-model="scope.row.state_value"
                size="medium"
                clearable
                @change="handleGetBindMailTemplate(scope.row)"
              >
                <el-option
                  v-for="(item,index) in scope.row.states"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
              <el-button
                size="medium"
                type="primary"
                :loading="scope.row.loading"
                @click="handleChangeOrderState(scope.row)"
              >修改状态
              </el-button>
              <el-tooltip :content="scope.row.waiting_pruchase ? '取消状态为代稍后处理': '调整状态位稍后处理'" placement="top">
                <el-switch
                  v-model="scope.row.waiting_pruchase"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleWaitingPurchaseOrder(scope.row)"
                />
              </el-tooltip>
              <el-button
                v-if="scope.row.bindmails.length === 0"
                size="medium"
                type="text"
                :loading="scope.row.loading"
                icon="el-icon-edit"
                @click="handleChangeBindMail(scope.row)"
              >绑定邮件
              </el-button>
              <el-button
                v-else
                size="medium"
                type="text"
                :loading="scope.row.loading"
                icon="el-icon-view"
                style="color:red;"
                @click="ShowBindMail(scope.row)"
              >已绑模板
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="order_datas.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,50,100,200,300,500]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <span v-if="total_sales > 0" style="float: right">总销售额:{{ total_sales }}</span>
      </el-main>
      <shipping
        :psorder_id="psorder_id"
        :shipping-visiable="shippingVisiable"
        :total_sales="shipping_total_sales"
        @closeMyDialog="shippingVisiable=false"
        @SetShippingSuccess="handleSetShippingSuccess"
      />
      <payment
        :orderpayment-visual="searchByPamentVisual"
        @closeMyDialog="searchByPamentVisual=false"
      />
      <shippingsearch
        :shippingsearch-visual="shippingsearchVisual"
        @closeMyDialog="shippingsearchVisual=false"
      />
      <aliexpressorders
        :aliexpressorder-visual="aliexpressordersVisual"
        @closeMyDialog="aliexpressordersVisual=false"
      />
      <orderstatics
        :order-static-visible="orderStaticVisible"
        :website_id="current_website_id"
        @closeMyDialog="orderStaticVisible=false"
      />
      <orderdetail
        :order-static-visible="orderdetailVisual"
        :product_url="product_url"
        :website_id="select_web"
        @closeMyDialog="orderdetailVisual=false"
      />
      <sendgoogleconversion
        :product_id="product_id"
        :show-dialog="sendgoogleconversionVisuable"
        @closeMyDialog="sendgoogleconversionVisuable=false"
      />
      <supplier
        :d-visible="supplierVisible"
        :original_url="original_url"
        :order_id="order_id"
        :image="product_image"
        @closeDialog="supplierVisible=false"
      />
      <ordersweb :d-visible="orderswebVisible" @closeDialog="orderswebVisible=false" />
      <feedfastmodify
        :domain="feedfastmodify_domain"
        :website_id="feedfastmodify_website_id"
        :product_id="feedfastmodify_product_id"
        :is-visual="feedFastModifyVisible"
        @closeMyDialog="feedFastModifyVisible=false"
      />
      <trackingfiles
        :trackingfiles-visible="trackingfilesVisible"
        @closeDialog="trackingfilesVisible=false"
      />
      <sendmail :dialog-visible="sendMailVisible" :mail_to="mail_to" @close="sendMailVisible=false" />
      <newemailbind
        :dialog-visible="bindmailDialogVisible"
        :website_domain="bindmailWebsiteDomain"
        :state_value="bindmailStateValue"
        :website_type="bindmailWebsiteType"
        @closeMyDialog="bindmailDialogVisible=false"
      />
      <blackaddress
        :blackaddress-visible="blackaddressVisible"
        @closeDialog="blackaddressVisible=false"
      />
      <refund
        :orderrefund-visual="refundVissual"
        :psorderpayment_id="psorderpayment_id"
        :title="refund_title"
        @searchOrder="handleSearchOrder"
        @closeMyDialog="refundVissual=false;psorderpayment_id=''"
      />
    </el-container>
  </div>

</template>

<script>
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
import { Post as AddOrderWeb, Get as GetOrderWebs } from '@/api/orders/psorderweb'
import { Get as GetOrders, Put as ModifyOrder } from '@/api/orders/psorder'
import { OrdersSyncState, OrdersGetPayment, OrdersSyncOrder, GetPaymentStatus } from '@/api/orders/ordersapi'
import { Get as GetOrderState } from '@/api/orders/psorderstate'
import { Get as GetBindTemplate } from '@/api/eco/emailtemplatewebstiestatebind'
import { AddOrderAddressBlack } from '@/api/orders/blackaddress'

import shipping from '@/views/orders/element/shipping'
import payment from '@/views/orders/element/payment'
import shippingsearch from '@/views/orders/element/shippingsearch'
import orderstatics from '@/views/orders/element/orderStatics'
import orderdetail from '@/views/orders/element/orderdetail'

import qs from 'qs'

import Cookies from 'js-cookie'
import Aliexpressorders from './element/aliexpressorders'
import Sendgoogleconversion from './element/sendgoogleconversion'
import Supplier from './element/supplier'
import Ordersweb from './element/ordersweb'
import Feedfastmodify from './element/feedfastmodify'
import Trackingfiles from './element/trackingfiles'
import Sendmail from '../email/element/sendmail'
import Newemailbind from '../email/element/newemailbind'
import Blackaddress from './element/blackaddress'
import refund from './element/refund'

export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  return Cookies.set(key, value, { expires: 30 })
}

const ProjectKey = 'orders_project_id'
export default {
  name: 'Orders',
  components: {
    refund,
    Blackaddress,
    Newemailbind,
    Sendmail,
    Trackingfiles,
    Feedfastmodify,
    Ordersweb,
    Supplier,
    Sendgoogleconversion,
    orderdetail,
    orderstatics,
    Aliexpressorders,
    shipping,
    payment,
    shippingsearch
  },
  data() {
    return {
      base_api: '',
      blackaddressVisible: false,
      bindmailDialogVisible: false,
      bindmailWebsiteDomain: '',
      bindmailStateValue: 2,
      bindmailWebsiteType: 'PrestaShop',
      mail_to: '',
      sendMailVisible: false,
      trackingfilesVisible: false,
      feedFastModifyVisible: false,
      feedfastmodify_domain: '',
      feedfastmodify_website_id: '',
      feedfastmodify_product_id: '',
      feedoptions: {},
      orderswebVisible: false,
      supplierVisible: false,
      original_url: '',
      product_image: '',
      order_id: '',
      sendgoogleconversionVisuable: false,
      product_id: '',
      product_url: '',
      orderdetailVisual: false,
      current_website_id: '',
      orderStaticVisible: false,
      aliexpressordersVisual: false,
      projects: [],
      project_id: null,
      projectsLoading: false,
      timerange: '',
      total_sales: 0,
      shippingsearchVisual: false,
      refundVissual: false,
      searchByPamentVisual: false,
      psorder_id: '',
      shippingVisiable: false,
      shipping_total_sales: 0,
      statesyncloading: false,
      headerStyle: "{color:'black'}",
      loading: false,
      select_web: '',
      website_options: [],
      remoteSearchWebsite_loading: false,
      selected_status: '',
      dataStatus: [],
      kwInput: '',
      order_by: 'order_time',
      order_desc: 1,
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      websites: [],
      orderwebs: [],
      order_datas: [],
      common_dataStatus: [
        {
          id: 101,
          name: '新订单',
          value: 'neworder'
        },
        {
          id: 102,
          name: '待采购',
          value: 'waiting_pruchase'
        },
        {
          id: 1,
          name: '状态1',
          value: 1
        },
        {
          id: 2,
          name: 'Payment accepted(2)',
          value: 2
        },
        {
          id: 3,
          name: 'Processing in progress(3)',
          value: 3
        },
        {
          id: 4,
          name: 'Shipped(4)',
          value: 4
        },
        {
          id: 5,
          name: 'Delivered(5)',
          value: 5
        },
        {
          id: 6,
          name: 'Canceled(6)',
          value: 6
        },
        {
          id: 7,
          name: 'Refunded(7)',
          value: 7
        },
        {
          id: 8,
          name: 'Payment error(8)',
          value: 8
        },
        {
          id: 9,
          name: 'On backorder (paid)(9)',
          value: 9
        },
        {
          id: 10,
          name: '10',
          value: 10
        },
        {
          id: 11,
          name: '11',
          value: 11
        },
        {
          id: 12,
          name: '12',
          value: 12
        },
        {
          id: 13,
          name: '13',
          value: 13
        },
        {
          id: 14,
          name: '14',
          value: 14
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime())
            start.setHours(0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天下班后',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            start.setHours(19, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '过去14天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近6个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }
        ]
      },
      psorderpayment_id: '',
      refund_title: '新增退款',
      bindmails: []
    }
  },
  created() {
    this.project_id = getToken(ProjectKey)
    this.handleFetchProjects()
    // this.handleGetWebsite()
  },
  methods: {
    handleSearchOrder(id) {
      this.kwInput = id
      this.handleGetOrders()
    },
    GetOrderPaymentStatus(row) {
      GetPaymentStatus({ psorder_id: row.id, id_transaction: row.id_transaction }).then(response => {
        this.$alert('支付状态:' + response.data, '支付结果', {
          confirmButtonText: '关闭',
          callback: action => {
            this.$message({
              type: 'info',
              message: `action: ${action}`
            })
          }
        })
      }).catch(err => {
        console.table(err)
      })
    },
    showRefund(row) {
      this.psorderpayment_id = row.psorderpayment_id
      this.refundVissual = true
      this.refund_title = row.domain + '订单:' + row.id_order + '新增退款'
    },
    handleAddOrderToBlackAddress(row) {
      AddOrderAddressBlack({ 'id': row.id })
        .then(response => {
          this.notify('添加成功')
        }).catch(err => {
          console.table(err)
        })
    },
    handleGetBindMailTemplate(row) {
      GetBindTemplate(null, qs.stringify({
        domain: row.domain,
        state_value: row.state_value
      }))
        .then(response => {
          row.bindmails = response.data.data
        }).catch(err => {
          console.table(err)
        })
    },
    ShowBindMail(row) {
      let message = '<ul>'
      for (let i = 0; i < row.bindmails.length; i++) {
        message += '<li>状态:' + row.bindmails[i].state_value + '  绑定模板:' + row.bindmails[i]['emailtemplate__name'] + '</li>'
      }
      message += '</ul>'
      this.$alert(message, '已经绑定模板', {
        dangerouslyUseHTMLString: true
      })
    },
    handleChangeBindMail(row) {
      this.bindmailStateValue = row.state_value
      this.bindmailWebsiteDomain = row.domain
      this.bindmailWebsiteType = row.website_type
      this.bindmailDialogVisible = true
    },
    handleReplyMail(row) {
      this.mail_to = row.email
      this.sendMailVisible = true
    },
    handleShowMail(row) {
      // this.$router.push({ name: 'emailbox', query: { k: row.email }})
      const link = this.$router.resolve({ name: 'emailbox' })
      const url = window.location.href.split('#')[0] + link.href
      console.log(url + '?k=' + row.email)
      window.open(url + '?k=' + row.email, '_blank')
    },
    handleShowSupplier(row) {
      this.original_url = row.product_url
      this.order_id = row.order_id
      this.product_image = row.image
      this.supplierVisible = true
    },
    handleShowOrderDetailAll() {
      this.product_url = ''
      this.orderdetailVisual = true
    },
    handleShowProductDetail(row) {
      this.product_url = row.product_url
      this.orderdetailVisual = true
    },
    handleShowFastModifyFeed(row) {
      if (row.product_id === '') {
        this.$message({
          type: 'info',
          message: '产品ID不能为空'
        })
        return
      }
      this.feedfastmodify_domain = row.domain
      this.feedfastmodify_website_id = row.website_id
      this.feedfastmodify_product_id = row.product_id
      console.log(this.feedfastmodify_domain, this.feedfastmodify_product_id)
      this.feedFastModifyVisible = true
    },
    handleShowGoogleConversion(row) {
      this.product_id = row.id
      this.sendgoogleconversionVisuable = true
    },
    handleFetchProjects() {
      this.projectsLoading = true
      GetProjects()
        .then(response => {
          this.projectsLoading = false
          this.projects = response.data.data
          if (this.projects.length) {
            this.project_id = getToken(ProjectKey) || null
          }
        })
        .catch(e => {
          this.projectsLoading = false
        })
    },
    tableRowStyle({ row, rowIndex }) {
      if (row.state_value === 8) {
        return 'background-color: pink;border-style: solid;'
      } else {
        return 'border-style: solid; border-width:5px;'
      }
    },
    tableCellStyle({ row, rowIndex }) {
      return 'border-right:1px solid #EBEEF5;border-bottom:2px solid #000'
    },
    handleSelectionChange(val) {
      this.total_sales = 0
      val.forEach((row) => {
        this.total_sales += row.total_paid
      })
    },
    handleWaitingPurchaseOrder(row) {
      ModifyOrder(row.id, { 'waiting_pruchase': row.waiting_pruchase })
        .then(() => {
          if (row.waiting_pruchase) {
            this.delData(row.id)
          }
          this.$message({
            type: 'success',
            message: '已设置ID:' + row.id + '状态成功'
          })
        })
    },
    handleDiedOrder(row) {
      this.$confirm('是否设置此订单为死单,不会再搜索结果中显示', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ModifyOrder(row.id, { 'died': !row.died })
          .then(() => {
            this.delData(row.id)
            this.$message({
              type: 'success',
              message: '已设置ID:' + row.id + '死单成功'
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消设置死单'
        })
      })
    },
    handleHiddenOrder(row) {
      this.$confirm('是否删除此订单,不会再搜索结果中显示', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ModifyOrder(row.id, { 'show_able': !row.show_able })
          .then(() => {
            this.delData(row.id)
            this.$message({
              type: 'success',
              message: '已删除ID:' + row.id + '成功'
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleReFreshOrder(row) {
      OrdersSyncOrder(row.id).then(() => {
        this.$notify({
          title: '成功',
          message: '同步成功',
          type: 'success',
          duration: 1000
        }).catch(error => {
          this.$message({
            type: 'error',
            message: error
          })
        })
        this.handleGetOrders()
      })
    },
    handleGetOrderState() {
      GetOrderState(null, qs.stringify({ 'website_id': this.select_web }))
        .then(response => {
          this.dataStatus = response.data.data
          console.log(this.dataStatus)
        }).catch(error => {
          this.$message({
            type: 'error',
            message: error
          })
        })
    },
    handleShipped(row) {
      this.psorder_id = row.id
      this.shippingVisiable = true
      this.shipping_total_sales = row.total_paid
    },
    handleSetShippingSuccess(data) {
      ModifyOrder(data.psorder_id, { 'is_shipping': true })
        .then(response => {
          this.$notify({
            title: '成功',
            message: '标记成功',
            type: 'success',
            duration: 1000
          })
        }).catch(error => {
          this.$message({
            type: 'error',
            message: error
          })
        })
    },
    delData(id) {
      this.order_datas.forEach((v, i) => {
        if (id === v.id) {
          console.log('delete row')
          this.order_datas.splice(i, 1)
        }
      })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.handleGetOrders()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.handleGetOrders()
    },
    handleSyncOrderState() {
      this.statesyncloading = true
      OrdersSyncState(this.select_web).then(response => {
        this.handleGetOrderState()
        this.statesyncloading = false
      }).catch(error => {
        this.statesyncloading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    handleStatics() {
      this.current_website_id = this.select_web
      this.orderStaticVisible = true
    },
    handleSingleStatics(website_id) {
      this.current_website_id = website_id
      this.orderStaticVisible = true
    },
    rowStyle({ row, rowIndex }) {
      if (row.is_shipping) {
        return 'background:#ffcc66;'
      } else {
        return ''
      }
    },
    handleGetWebsite() {
      GetWebsite(null, qs.stringify({ 'project_id': this.project_id })).then(response => {
        this.websites = response.data.data
      })
    },
    handleGetOrderWebs() {
      GetOrderWebs().then(response => {
        this.orderwebs = response.data.data
        console.log(this.orderwebs)
      })
    },
    handleChangeOrderState(row) {
      this.$confirm(`确认要修改订单状态吗？状态修改会同步到网站`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.loading = true
        ModifyOrder(row.id, { 'state_value': row.state_value })
          .then(response => {
            row.loading = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 1000
            })
            this.delData(row.id)
          })
      }).catch(() => {
      })
    },
    getAddressJs(row) {
      this.$alert(row.js, row.domain + '订单' + row.id_order + '地址代码', {
        confirmButtonText: '确定'
      })
      this.$copyText(row.js).then(response => {
        this.$notify({
          title: '成功',
          message: '订单' + row.id_order + '地址代码已经复制到了剪切板',
          type: 'success'
        })
      }).catch(() => {
        this.$notify({
          title: '提示',
          type: 'error',
          message: '地址代码复制成功'
        })
      })
    },
    addnote(row) {
      this.$prompt('添加备注', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.note
      }).then(({ value }) => {
        this.loading = true
        ModifyOrder(row.id, { 'note': value })
          .then(response => {
            this.loading = false
            row.note = value
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 1000
            })
          }).catch(error => {
            this.loading = false
            this.$message({
              type: 'error',
              message: error
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleSyncOrders() {
      this.loading = true
      AddOrderWeb({ website_id: this.select_web }).then(response => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 1000
        })
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    handleGetPayment(row) {
      this.loading = true
      OrdersGetPayment(row.id).then(response => {
        this.loading = false
        row['id_transaction'] = response.data.id_transaction
        row['payment_name'] = response.data.payment_name
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 1000
        })
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    handleChangeProject() {
      setToken(ProjectKey, this.project_id)
      // this.handleGetWebsite()
    },
    remoteSearchWebsite(query) {
      if (query !== '') {
        this.remoteSearchWebsite_loading = true
        GetWebsite(null, qs.stringify({
          kw: query,
          pagesize: 5,
          page: 1
        })).then(response => {
          // this.website_options = this.website_options.concat(response.data.data)
          const id_list = this.website_options.map(item => {
            return item.id
          })
          for (let i = 0; i < response.data.data.length; i++) {
            if (id_list.indexOf(response.data.data[i].id) === -1) {
              this.website_options.push(response.data.data[i])
            }
          }
          this.remoteSearchWebsite_loading = false
        })
      } else {
        this.remoteSearchWebsite_loading = false
      }
    },
    handleChangeWeb() {
      this.page = 1
      this.handleGetOrders()
      this.handleGetOrderState()
    },
    handleRefund() {
      this.refundVissual = true
    },
    handleSearchByPayment() {
      this.searchByPamentVisual = true
    },
    handleSearchShipping() {
      this.shippingsearchVisual = true
    },
    handleAliexpressOrders() {
      this.aliexpressordersVisual = true
    },
    handleGetOrders() {
      this.loading = true
      // if (this.kwInput !== '') {
      //   this.page = 1
      // }
      GetOrders(null, qs.stringify({
        project_id: this.project_id,
        website_id: this.select_web,
        kw: this.kwInput,
        pagesize: this.pagesize,
        start: this.timerange ? this.timerange[0] : '',
        end: this.timerange ? this.timerange[1] : '',
        page: this.page,
        order_by: this.order_by,
        state: this.selected_status.join('-'),
        order_desc: this.order_desc
      })).then(response => {
        this.order_datas = response.data.data
        this.total_sales = 0
        setToken(ProjectKey, this.project_id)
        this.order_datas.forEach((row) => {
          this.total_sales += row.total_paid
        })
        this.loading = false
        this.total = response.data.total
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    }
  }
}
</script>

<style scoped>
.app-container >>> table, tr {
  border-color: black;
}

.app-container >>> .el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.app-container >>> .el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.app-container >>> .el-carousel__button {
  background-color: red;
}

.el-header {
  height: 120px;
}

.el-header, .el-footer {
  background-color: #00c0ef;
  color: white;
}

.el-container >>> .pointer {
  cursor: pointer;
  color: #409EFF;
}

.el-container >>> a:visited {
  color: purple;
}

.el-container >>> a:link {
  color: #409EFF;
}

.el-container >>> a:active {
  color: red;
}

.app-container >>> a:hover {
  color: red;
  text-decoration: underline;
}
</style>
